package com.eshin.connectionfactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;

public class MyConnectionFactory implements ConnectionFactory{
	
	protected AtomicInteger count = new AtomicInteger(0);
	List<CachingConnectionFactory>connectionFactoryList = new ArrayList<>();
	List<CachingConnectionFactory>unReachableconnectionFactoryList = new ArrayList<>();
	int retryInterval = 3;
	
	public MyConnectionFactory(List<CachingConnectionFactory>connectionFactoryList) {
		this.connectionFactoryList = connectionFactoryList;
	}
	public MyConnectionFactory(List<CachingConnectionFactory>connectionFactoryList,int retryInterval) {
		this.connectionFactoryList = connectionFactoryList;
		this.retryInterval = retryInterval;
	}
	
	public void initExecutorService(){
		ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
		scheduledExecutorService.scheduleAtFixedRate(new ReTryConnectionRunable(), retryInterval, retryInterval, TimeUnit.SECONDS);
	}
	@Override
	public Connection createConnection() throws AmqpException {
		int addSize = connectionFactoryList.size();
		int index = count.getAndIncrement() % addSize;
		Connection con = null;
		try {
			con =connectionFactoryList.get(index).createConnection();
		} catch (Exception e) {
			con = continueTogetCon(index);
		}
		return con;
	}
	
	/**
	 * 获取connection失败后重新找一个地址，失败的地址从connectionFactoryList移到unReachableconnectionFactoryList
	 * 失败的地址另起线程定时尝试连接，连接成功则放回connectionFactoryList
	 * @param index
	 * @return
	 */
	private synchronized Connection continueTogetCon(int index) {
		Connection con = null;
		int leftSize = connectionFactoryList.size();
		/**
		 * 保证至少有一个地址保留
		 */
		if(leftSize == 1){
			return null;
		}
		CachingConnectionFactory unreachableConnectionFactory = connectionFactoryList.remove(index);
		/**
		 * 有可能多个线程同时在同一个index等待进入方法
		 */
		if( null != unreachableConnectionFactory){
			unReachableconnectionFactoryList.add(unreachableConnectionFactory);
		}
		
		/**
		 * 找到第一个可用连接
		 */
		for(int i=0;i<leftSize-1;i++){
			try {
				con = connectionFactoryList.get(i).createConnection();
			} catch (AmqpException e) {
				if(i == leftSize -1){
					System.out.println("no available connectFactory...");
					throw e;
				}else {
					continue;
				}
				
			}
		}
		return con;
	}
	
	class ReTryConnectionRunable implements Runnable{

		@Override
		public void run() {
			int size = unReachableconnectionFactoryList.size();
			System.out.println("unReachableconnectionFactoryList size:"+size);
			if(0 < size){
				CachingConnectionFactory unReachableconnectionFactory = unReachableconnectionFactoryList.get(0);
				System.out.println("retry connect :"+unReachableconnectionFactory.getHost()+":"+unReachableconnectionFactory.getPort());
				try {
					Connection con = unReachableconnectionFactory.createConnection();
					if(null != con){
						System.out.println("recover :"+unReachableconnectionFactory.getHost()+":"+unReachableconnectionFactory.getPort());
						connectionFactoryList.add(unReachableconnectionFactoryList.remove(0));
					}
				} catch (AmqpException e) {
					System.out.println("fail to retry:"+unReachableconnectionFactory.getHost()+":"+unReachableconnectionFactory.getPort());
				}
			}
		}
		
	}
	@Override
	public String getHost() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public int getPort() {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	public String getVirtualHost() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String getUsername() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void addConnectionListener(ConnectionListener listener) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean removeConnectionListener(ConnectionListener listener) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public void clearConnectionListeners() {
		// TODO Auto-generated method stub
		
	}
	public List<CachingConnectionFactory> getConnectionFactoryList() {
		return connectionFactoryList;
	}
	public void setConnectionFactoryList(List<CachingConnectionFactory> connectionFactoryList) {
		this.connectionFactoryList = connectionFactoryList;
	}
}
